<template>
  <div class="bgOrderSelecServices h100">
    <a-form-model
      ref="formComp"
      :model="formData"
      :rules="rules"
      layout="horizontal"
      class="AsteriskAfter newEditStyle bgOrderSelecServicesForm"
    >
      <a-row style="margin-bottom: 20px">
        <!-- 选择服务类型 -->
        <a-col
          :xs="24"
          :sm="24"
          :md="6"
          :lg="10"
          :xl="8"
          :xxl="8">
          <div class="lh30">
            <a-radio-group :value="formData.serviceType" @change="changeSelectServiceType">
              <a-radio :value="'getEffectiveService'">
                {{ $t('effectiveService') }}
              </a-radio>
              <a-radio :value="'getNotEffectiveService'">
                {{ $t('notEffectiveService') }}
              </a-radio>
            </a-radio-group>
          </div>
        </a-col>
        <!-- 有效期 -->
        <a-col
          :xs="24"
          :sm="17"
          :md="12"
          :lg="10"
          :xl="10"
          :xxl="8">
          <div class="lh30">
            <span style="margin-right: 8px">{{ $t('openingValidityYear') }}</span>
            <a-input-number
              :min="1"
              :max="999"
              :precision="0"
              v-model="formData.year"
              style="width: 40%; height: 30px; line-height: 30px; vertical-align: middle"
              size="small"
            />
            <a-select style="width:80px;margin-left:10px" v-model="formData.yearType">
              <a-select-option
                v-for="(item,index) in typeYearArr"
                :key="index"
                :value="item.value"
                :title="$t(item.name)"
              >
                <span>{{ $t(item.name) }}</span>
              </a-select-option>
            </a-select>
            <question-mark-tip
              :tip-title="$t('yearTypeTip')"
              :popupContainer="$commonFun.getPopupContainer"
            ></question-mark-tip>
          </div>
        </a-col>
        <a-col
          :xs="24"
          :sm="7"
          :md="6"
          :lg="4"
          :xl="6"
          :xxl="8">
          <div style="text-align: right" class="lh30">
            <span style="margin-right: 8px">{{ $t('selectedVehicles') }}</span>
            <span>{{ info ? info.total : '-' }}</span>
          </div>
        </a-col>
      </a-row>
    </a-form-model>

    <!-- 服务列表 -->
    <div class="bgOrderSelecServicesTable" ref="bgOrderSelecServicesTable">
      <s-table
        class="h100"
        :columns="columns"
        :scrollX="800"
        :data-source="serviceLists"
        :showPagination="false"
        :loading="loading"
        :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
        row-key="serviceCode"
      >
        <template slot-scope="text" v-for="column in commonColumns" :slot="column.scopedSlots">
          <table-ellipsis :text="text || '-'" :key="column.dataIndex"></table-ellipsis>
        </template>
        <template #presetOrNot="text">
          <table-ellipsis :text="$t(text ? 'yes' : 'no')"></table-ellipsis>
        </template>
        <template #whetherSold="text">
          <table-ellipsis :text="$t(text ? 'yes' : 'no')"></table-ellipsis>
        </template>
        <template #needToLearn="text">
          <table-ellipsis :text="$t(text ? 'yes' : 'no')"></table-ellipsis>
        </template>
        <template #whetherActivated="text">
          <table-ellipsis :text="$t(text ? 'yes' : 'no')"></table-ellipsis>
        </template>
        <template #versionDepend="text, record">
          <a @click="handleVersionDepend(record)">{{ $t('view') }}</a>
        </template>
        <template #publishStatus="text">
          <a-tag v-if="servicePublishStatusDictCodeObj[text]" :color="servicePublishStateObj[text].color">
            {{ servicePublishStatusDictCodeObj[text] }}
          </a-tag>
          <span v-else>_</span>
        </template>
        <template #serviceExpireDate="text, record, index">
          <a-date-picker
            :key="record.serviceCode"
            :disabledDate="disabledDate"
            @change="
              (val, dateString) => {
                onChangeDate(val, dateString, record, index)
              }
            "
            :value="getDatePickerValue(record.expiration)"
            :getCalendarContainer="getCalendarContainer"
            style="width: 100%"
          />
        </template>
      </s-table>
    </div>
    <service-version-depend :serviceId="serviceId" ref="versionDependRef"> </service-version-depend>
  </div>
</template>
<script>
import { mapState } from 'vuex'
import CarModelSelect from '@/views/components/CarModelSelect'
import STable from '@/components/Table'
import { bgOrderServiceTbColumns } from '../config/list'
import tableEllipsis from '@/components/Ellipsis/TableEllipsis'
import serviceApi from '@/api/modules/software/serviceConfig'
import moment from 'moment'
import ServiceVersionDepend from '@/views/components/ServiceVersionDepend.vue'
import QuestionMarkTip from '@/views/components/QuestionMarkTip'

export default {
  components: {
    CarModelSelect,
    STable,
    tableEllipsis,
    ServiceVersionDepend,
    QuestionMarkTip
  },
  props: {
    time: {
      type: Number,
      default: 10230
    },
    isBack: {
      type: Boolean,
      default: false
    },
    info: {
      type: Object,
      default () {
        return {}
      }
    }
  },
  computed: {
    ...mapState({
      servicePublishStateObj: (state) => state.dict.servicePublishStateObj
    }),
    commonColumns () {
      return this.columns.filter((item) => !item.special)
    },
    servicePublishStatusDictCodeObj () {
      return this.$store.getters.getDictCodeObj('servicePublishStatusDictCode')
    },
    formData () {
      return this.$store.state.orderManagement.bgOrderFormData
    }
  },
  data () {
    return {
      typeYearArr: [
        { value: 1, name: 'month' },
        { value: 2, name: 'year' }
      ],
      columns: bgOrderServiceTbColumns,
      rules: null,
      loading: false,
      serviceLists: [],
      serviceId: '',
      selectedVehicleTotal: 0,
      selectedRowKeys: []
    }
  },
  mounted () {
    this.changeColums()
  },

  watch: {
    time: {
      handler () {
        this.getCarModelServiceData()
      },
      immediate: true
    }
  },
  created () {
    this.$store.dispatch('getServicePublishStatusDictCodeData')
  },
  methods: {
    onSelectChange (selectedRowKeys) {
      console.log(selectedRowKeys, 'selectedRowKeys')
      this.selectedRowKeys = selectedRowKeys
    },
    changeColums () {
      // 不能重新给this.columns赋值 否者表格无法拖动
      const statusColums = {
        title: this.$t('publishState'),
        dataIndex: 'publishStatus',
        scopedSlots: { customRender: 'publishStatus' },
        width: 180
      }
      const columnhasStatus = this.columns.filter(item => item.dataIndex === 'publishStatus')
      // 如果是待生效 且没有状态列 则需要加状态列
      if (this.formData.serviceType === 'getNotEffectiveService' && !columnhasStatus.length) {
        this.columns.push(statusColums)
      }
      // 如果是已生效服务 有状态列 则需要去掉状态列
      if (this.formData.serviceType === 'getEffectiveService' && columnhasStatus.length) {
        this.columns.pop()
      }
    },
    changeSelectServiceType (ev) {
      sessionStorage.removeItem('selectedService')
      this.formData.serviceType = ev.target.value
      this.changeColums()
      this.getCarModelServiceData()
    },
    // 选择车型
    changeModelBefore (val) {
      this.formData.modelId = val
      const obj = this.$refs.carModelSelectRef.modelOptions.find((item) => item.id === val)
      if (obj) {
        this.formData.modelCode = obj.code
        this.formData.trimLevel = obj.trimLevel
        this.formData.modelName = obj.title
      }
      this.getCarModelServiceData()
    },
    // 获取车型上已生效的服务
    getCarModelServiceData () {
      this.serviceLists = []
      if (!this.info.modelId) {
        return
      }
      const method = this[this.formData.serviceType]
      if (method) {
        this.loading = true
        method()
      }
    },
    // 获取已生效的服务
    getEffectiveService () {
      serviceApi
        .getAuditedService({
          modelId: this.info.modelId
        })
        .then((res) => {
          this.serviceLists = this.setServiceDefaultDate(res.data)
        })
        .finally(() => {
          this.loading = false
        })
    },
    // 获取待生效的服务
    getNotEffectiveService () {
      serviceApi
        .getIneffectiveService({
          modelId: this.info.modelId
        })
        .then((res) => {
          this.serviceLists = this.setServiceDefaultDate(res.data)
        })
        .finally(() => {
          this.loading = false
        })
    },
    setServiceDefaultDate (data) {
      const selectedService = JSON.parse(sessionStorage.getItem('selectedService'))
      this.selectedRowKeys = selectedService || []
      return data
    },
    resetData () {
      this.$store.commit('resetOrderManagementBgOrderFormData')
      this.serviceLists = []
    },
    onChangeDate (val, dateString, record, index) {
      // eslint-disable-next-line no-param-reassign
      record.expiration = dateString
      this.$set(this.serviceLists, index, { ...record })
    },
    getDatePickerValue (dateString) {
      if (!dateString) return null
      return moment(dateString)
    },
    getCalendarContainer () {
      return this.$refs.bgOrderSelecServicesTable
    },
    disabledDate (current) {
      return current <= moment().subtract(1, 'day')
    },
    handleVersionDepend (record) {
      this.serviceId = record.serviceId
      this.$nextTick(() => {
        this.$refs.versionDependRef.visible = true
      })
    },
    getFormData () {
      return new Promise((resolve) => {
        if (/[^\d]/.test(this.formData.year)) {
          this.$message.error(this.$t('pleaseInput') + this.$t('openingValidityYear').toLowerCase())
          return
        }
        if (this.selectedRowKeys.length === 0) {
          this.$message.error(this.$t('pleaseSelect') + this.$t('service').toLowerCase())
          return
        }
        const serviceLists = []
        this.serviceLists.forEach((item) => {
          if (this.selectedRowKeys.includes(item.serviceCode)) {
            serviceLists.push({
              serviceCode: item.serviceCode,
              serviceName: item.serviceName
            })
          }
        })
        if (serviceLists.length === 0) {
          this.$message.error(this.$t('pleaseInput') + this.$t('openingValidityYear'))
          return
        }
        const formData = JSON.parse(JSON.stringify(this.$store.state.orderManagement.bgOrderFormData))
        if (typeof formData.vehicleType === 'undefined') {
          delete formData.vehicleType
        }
        if (typeof formData.province === 'undefined') {
          formData.province = ''
        }
        formData.modelCode = this.info.modelCode
        formData.modelName = this.info.modelName
        formData.trimLevel = this.info.trimLevel
        formData.modelId = this.info.modelId
        formData.serviceList = serviceLists
        if (formData.isCustomSelect) {
          formData.vehicleSourceType = 2
        }
        delete formData.isCustomSelect
        delete formData.uploadResult
        delete formData.fileName
        delete formData.serviceType
        delete formData.modelId1
        delete formData.modelId2
        resolve(formData)
      })
    },
    // 保存上一次填写的服务到期日期(点上一步再到下一步的时候需要)
    saveServicePrevDate () {
      sessionStorage.setItem('selectedService', JSON.stringify(this.selectedRowKeys))
    }
  },
  beforeDestroy () {
    this.saveServicePrevDate()
  }
}
</script>
<style lang="less" scoped>
.bgOrderSelecServices {
  display: flex;
  flex-direction: column;

  .bgOrderSelecServicesForm {
    flex: none;
  }

  .bgOrderSelecServicesTable {
    flex: 1 0 0;
    min-height: 400px;
  }
  .lh30 {
    line-height: 24px;
  }
}
</style>
<style lang="less">
.bgOrderSelecServices {
  .ant-calendar-picker-container-content {
    width: 100%;
  }
}
</style>
